//
//  XMTextView.m
//  XMWeibo
//
//  Created by chi on 14-8-29.
//  Copyright (c) 2014年 xiaoming. All rights reserved.
//

#import "XMTextView.h"

#import "XMSelectedPhotosView.h"

@interface XMTextView ()

/** placeholder label */
@property (nonatomic, weak) UILabel *placeholderLabel;


/** 照片展示视图 */
@property (nonatomic, weak) XMSelectedPhotosView *selectPhotosView;

@end

@implementation XMTextView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.alwaysBounceVertical = YES;
        self.font = [UIFont systemFontOfSize:15.0f];
        
        // 添加placeholder
        UILabel *label = [[UILabel alloc]init];
        label.numberOfLines = 0;
        label.font = self.font;
        label.textColor = [UIColor lightGrayColor];
        self.placeholderLabel = label;
        self.placeholderLabel.hidden = YES;
        [self addSubview:label];
        
        // 创建照片展示图
        XMSelectedPhotosView *photosView = [[XMSelectedPhotosView alloc]init];
        self.selectPhotosView = photosView;
        
        [self addSubview:photosView];
        
        // 添加通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textViewTextChange:) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}

#pragma mark - 添加image
- (void)addImage:(UIImage *)image
{
    [self.selectPhotosView addImage:image];
}


#pragma mark - 重写images get方法
- (NSMutableArray *)images
{
    return self.selectPhotosView.images;
}

#pragma mark -

/**
 *  设置选中文字
 */
- (void)setPlaceholderText:(NSString *)placeholderText
{
    _placeholderText = placeholderText;
    
    if (placeholderText.length > 0) {
        self.placeholderLabel.hidden = NO;
        self.placeholderLabel.text = placeholderText;
        
        CGFloat edgeY = 6.0;
        CGFloat edgeX = 6.0;
        if (!isIOS7) {
            edgeX = 12.0;
            edgeY = 8.0;
        }

        CGSize size = [placeholderText sizeWithFont:self.font constrainedToSize:CGSizeMake(self.bounds.size.width - edgeX * 2, self.bounds.size.height)];


        
        self.placeholderLabel.frame = (CGRect){CGPointMake(edgeX, edgeY), size};
        
    }
    else {
        self.placeholderLabel.hidden = YES;
    }
    
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.selectPhotosView.frame = CGRectMake(0.0, 90.0, self.frame.size.width, self.frame.size.width / 5 * 2);
}

/**
 *  修改placeholder状态
 */
- (void)textViewTextChange:(NSNotification*)notification
{
    if (_placeholderText.length > 0) {
        self.placeholderLabel.hidden = self.text.length > 0;
    }
}


@end
